package com.four.project.shiro;

import com.four.project.dao.ManagerMapper;
import com.four.project.dao.MenuMapper;
import com.four.project.pojo.Manager;
import com.four.project.pojo.Menu;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @Description
 * @Author 梯子君(xie)
 * @Data 2020/7/911:38
 */

public class MyRealm extends AuthorizingRealm {

    @Autowired
    ManagerMapper managerMapper;
    @Autowired
    MenuMapper menuMapper;

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        String username =(String) principalCollection.getPrimaryPrincipal();
        //授权信息对象
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        //查询该管理员名下权限
        List<Menu> list = menuMapper.selectmenu(username);
        Set menu =new HashSet();
        for (Menu m: list) {
            menu.add(m.getMenu());
        }
        //将该用户权限放入授权信息对象中
        simpleAuthorizationInfo.setStringPermissions(menu);
        return null;
    }
    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //获取输入名称
        String username = (String)authenticationToken.getPrincipal();
        //输入名称查询该对象
        Manager queryManager = managerMapper.findByUserName(username);
        //创建一个验证消息对象
        SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(username,queryManager.getPassword(),getName());
        return simpleAuthenticationInfo;
    }
}
